<template>
  <div class="login-container">
    <!-- 顶部装饰条 -->
    <div class="top-bar"></div>
    
    <div class="login-box">
      <div class="logo-area">
        <h1 class="app-title">体育应用</h1>
        <p class="welcome-text">欢迎登录</p>
      </div>
      
      <div class="form-area">
        <nut-form ref="formRef" :model="formModel" :rules="rules" label-position="top" validate-trigger="onBlur">
          <!-- 用户名输入 -->
          <nut-form-item label="" prop="username" class="mobile-form-item">
            <div class="input-wrapper" :class="{ 'input-error': errors.username }">
              <span class="input-icon">{{ errors.username ? '⚠️' : '👤' }}</span>
              <nut-input
                v-model="formModel.username"
                placeholder="请输入用户名"
                :border="false"
                type="text"
                class="mobile-input"
                @focus="onInputFocus"
                @blur="handleInputBlur('username')"
                @input="handleInputChange('username')"
              />
            </div>
            <div v-if="errors.username" class="error-message">{{ errors.username }}</div>
          </nut-form-item>
          
          <!-- 密码输入 -->
          <nut-form-item label="" prop="password" class="mobile-form-item">
            <div class="input-wrapper" :class="{ 'input-error': errors.password }">
              <span class="input-icon">{{ errors.password ? '⚠️' : '🔒' }}</span>
              <nut-input
                v-model="formModel.password"
                placeholder="请输入密码"
                :border="false"
                type="password"
                class="mobile-input"
                @focus="onInputFocus"
                @blur="handleInputBlur('password')"
                @input="handleInputChange('password')"
              />
            </div>
            <div v-if="errors.password" class="error-message">{{ errors.password }}</div>
          </nut-form-item>
          
          <!-- 记住密码选项 -->
          <nut-form-item class="remember-item">
            <nut-checkbox v-model="formModel.remember" class="mobile-checkbox">记住密码</nut-checkbox>
          </nut-form-item>
          
          <!-- 登录按钮 -->
          <nut-form-item class="login-btn-item">
            <nut-button
              class="login-btn"
              type="primary"
              :loading="loading"
              @click="handleLogin"
            >
              登录
            </nut-button>
          </nut-form-item>
          
          <!-- 底部链接区域 -->
          <div class="bottom-links">
            <span class="link-text">忘记密码?</span>
            <span class="link-text">注册账号</span>
          </div>
        </nut-form>
      </div>
    </div>
    
    <!-- 底部版权信息 -->
    <div class="footer">
      <p class="copyright">© 2023 体育应用 版权所有</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from '@nutui/nutui'

// 路由
const router = useRouter()

// 表单引用
const formRef = ref()

// 加载状态
const loading = ref(false)

// 表单数据
const formModel = reactive({
  username: '',
  password: '',
  remember: false
})

// 错误信息对象
const errors = reactive({
  username: '',
  password: ''
})

// 表单验证规则 - 符合NutUI的FormRules类型定义
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, message: '用户名长度不能小于3位', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' },
    { 
      validator: (value: string) => {
        // 返回布尔值：true表示验证通过
        return !value || /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d@$!%*#?&]{6,}$/.test(value);
      },
      message: '密码必须包含字母和数字',
      trigger: 'blur'
    }
  ]
}

// 输入框焦点处理
const onInputFocus = (e: Event) => {
  const target = e.target as HTMLElement
  const inputWrapper = target.closest('.input-wrapper')
  if (inputWrapper) {
    inputWrapper.classList.add('input-focused')
  }
}

// 输入框失焦处理（增强版）
const handleInputBlur = async (field: string) => {
  const target = document.querySelector(`[prop="${field}"]`) as HTMLElement
  const inputWrapper = target?.querySelector('.input-wrapper')
  
  if (inputWrapper) {
    inputWrapper.classList.remove('input-focused')
  }
  
  // 对当前字段进行验证
  if (formRef.value) {
    try {
      await formRef.value.validateField(field)
      errors[field as keyof typeof errors] = ''
    } catch (err: any) {
      // 捕获验证错误并显示
      if (err && err.message) {
        errors[field as keyof typeof errors] = err.message
      }
    }
  }
}

// 输入框内容变化处理
const handleInputChange = (field: string) => {
  // 当用户开始输入时，清除该字段的错误信息
  if (errors[field as keyof typeof errors]) {
    errors[field as keyof typeof errors] = ''
  }
}

// 处理登录
  const handleLogin = async () => {
    try {
      // 重置所有错误信息
      errors.username = ''
      errors.password = ''
      
      // 验证表单
      await formRef.value?.validate()
      
      // 设置加载状态
      loading.value = true
      
      // 模拟登录请求
      setTimeout(() => {
        console.log('登录请求参数:', formModel)
        
        // 存储登录状态
        localStorage.setItem('token', 'mock_token_' + Date.now())
        
        if (formModel.remember) {
          localStorage.setItem('username', formModel.username)
          // 安全存储密码（实际项目中应加密）
          sessionStorage.setItem('password_remember', formModel.password)
        } else {
          localStorage.removeItem('username')
          sessionStorage.removeItem('password_remember')
        }
        
        // 显示成功提示
        showToast.success('登录成功', {
          duration: 2000,
          onClose: () => {
            // 跳转到首页
            router.push('/')
          }
        })
        
        // 恢复加载状态
        loading.value = false
      }, 1000)
    } catch (error: any) {
      // 恢复加载状态
      loading.value = false
      
      // 显示验证失败的全局提示
      showToast.text('请检查输入信息', {
        duration: 2000,
        icon: 'warning'
      })
      
      // 记录详细错误信息
      console.error('登录验证失败:', error)
    }
  }

// 初始化时检查是否有记住的用户信息
const initForm = () => {
  const savedUsername = localStorage.getItem('username')
  const savedPassword = sessionStorage.getItem('password_remember')
  
  if (savedUsername) {
    formModel.username = savedUsername
    formModel.remember = true
    
    // 如果同时保存了密码，也自动填充（实际项目中应谨慎处理）
    if (savedPassword) {
      formModel.password = savedPassword
    }
  }
}

// 组件挂载时初始化
onMounted(() => {
  initForm()
  
  // 为移动设备添加键盘事件监听
  window.addEventListener('keyboardWillShow', handleKeyboardShow)
  window.addEventListener('keyboardWillHide', handleKeyboardHide)
})

// 键盘显示时的处理
const handleKeyboardShow = () => {
  // 可以在这里调整布局，防止键盘遮挡输入框
  document.body.style.overflow = 'hidden'
}

// 键盘隐藏时的处理
const handleKeyboardHide = () => {
  document.body.style.overflow = 'auto'
}

// 清理事件监听
const cleanup = () => {
  window.removeEventListener('keyboardWillShow', handleKeyboardShow)
  window.removeEventListener('keyboardWillHide', handleKeyboardHide)
}

// 在组件卸载时清理
import { onUnmounted } from 'vue'
onUnmounted(() => {
  cleanup()
})
</script>

<style scoped lang="scss">
/* 全局重置 */
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

.login-container {
  min-height: 100vh;
  background-color: #f8f8f8;
  display: flex;
  flex-direction: column;
  padding: 0;
  position: relative;
  // 适配不同屏幕高度
  @media (max-height: 600px) {
    height: 100vh;
  }
}

/* 顶部装饰条 */
.top-bar {
  height: 4px;
  background: linear-gradient(90deg, #1890ff, #36cfc9);
  width: 100%;
}

.login-box {
  width: 100%;
  padding: 30px 20px 20px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

/* Logo区域 */
.logo-area {
  text-align: center;
  margin-bottom: 36px;
  padding-top: 20px;
  
  .app-title {
    font-size: 28px;
    font-weight: bold;
    color: #1890ff;
    margin-bottom: 8px;
    // 移动端字体优化
    letter-spacing: 1px;
  }
  
  .welcome-text {
    font-size: 16px;
    color: #666;
    font-weight: 400;
  }
}

/* 表单区域 */
.form-area {
  flex: 1;
  
  // 移动端表单项样式
  .mobile-form-item {
    padding: 0 0 16px 0;
    text-align: center;
    
    .input-wrapper {
      display: inline-flex;
      align-items: center;
      background-color: #fff;
      border-radius: 8px;
      padding: 0 16px;
      height: 48px;
      border: 1px solid #e8e8e8;
      transition: all 0.3s ease;
      width: 90%;
      max-width: 300px;
      
      &.input-focused {
        border-color: #1890ff;
        box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.1);
      }
      
      &.input-error {
        border-color: #f5222d;
        box-shadow: 0 0 0 2px rgba(245, 34, 45, 0.1);
      }
    }
  }
  
  // 错误提示信息
  .error-message {
    color: #f5222d;
    font-size: 12px;
    padding: 4px 0 0 0;
    line-height: 1.4;
    animation: fadeIn 0.3s ease-in-out;
  }
  
  // 错误提示动画
  @keyframes fadeIn {
    from {
      opacity: 0;
      transform: translateY(-2px);
    }
    to {
      opacity: 1;
      transform: translateY(0);
    }
  }
  
  // 输入框图标
  .input-icon {
    font-size: 18px;
    margin-right: 12px;
    color: #999;
  }
  
  // 移动端输入框
  .mobile-input {
    flex: 1;
    height: 100%;
    font-size: 16px;
    color: #333;
    // 适配iOS Safari的输入框样式
    :deep(input) {
      -webkit-appearance: none;
      border-radius: 0;
    }
    // 增加触摸区域
    :deep(.nut-input-wrapper) {
      padding: 12px 0;
    }
  }
  
  // 记住密码选项
  .remember-item {
    padding: 0 0 16px 0;
    text-align: center;
    
    .mobile-checkbox {
      font-size: 14px;
      color: #666;
      
      :deep(.nut-checkbox-label) {
        font-size: 14px;
      }
      
      // 增加触摸区域
      :deep(.nut-checkbox-container) {
        padding: 4px 0;
      }
    }
  }
  
  // 登录按钮项
  .login-btn-item {
    padding: 8px 0;
    margin-bottom: 24px;
    text-align: center;
    
    .login-btn {
      width: 90%;
      max-width: 300px;
      height: 48px;
      font-size: 18px;
      font-weight: 500;
      border-radius: 24px;
      background-color: #1890ff;
      display: inline-block;
      
      &:active {
        background-color: #096dd9;
      }
    }
  }
  
  // 底部链接区域
  .bottom-links {
    display: flex;
    justify-content: space-between;
    padding: 0 4px;
    width: 90%;
    max-width: 300px;
    margin: 0 auto;
    
    .link-text {
      font-size: 14px;
      color: #1890ff;
      text-decoration: none;
      // 增加触摸区域
      padding: 8px;
      display: inline-block;
      
      &:active {
        color: #096dd9;
        opacity: 0.8;
      }
    }
  }
}

/* 底部版权信息 */
.footer {
  padding: 16px 0;
  text-align: center;
  
  .copyright {
    font-size: 12px;
    color: #999;
  }
}

/* 响应式设计 */
@media (max-width: 320px) {
  .login-box {
    padding: 24px 16px 16px;
  }
  
  .app-title {
    font-size: 24px !important;
  }
  
  .login-btn {
    height: 44px !important;
    font-size: 16px !important;
  }
}

@media (min-height: 700px) {
  .login-box {
    justify-content: center;
  }
  
  .logo-area {
    padding-top: 40px;
  }
}
</style>
